<template>
  <el-dialog
    title="广告配置"
    class="edit-goods-dialog"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="handleCloseDialog"
    width="1200px"
  >
    <div class="app-container">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="未下单广告" name="tab1"
          ><span class="red"
            >可拖拽进行排序，排序越靠前越先被用户下单</span
          ></el-tab-pane
        >
        <el-tab-pane label="已下单广告" name="tab2"></el-tab-pane>
      </el-tabs>
      <div class="options-btns" v-if="activeName === 'tab1'">
        <el-button
          size="mini"
          type="primary"
          class="btn-add"
          @click="handleOption('1')"
          style="margin-left: 20px"
          >派发广告</el-button
        >
        <el-button
          size="mini"
          type="danger"
          class="btn-add"
          @click="handleOption('2')"
          style="margin-left: 20px"
          >取消派发</el-button
        >
        <el-button
          size="mini"
          type="success"
          class="btn-add"
          @click="handleAdd"
          style="margin-left: 20px"
          >添加广告配置</el-button
        >
      </div>
      <div
        :class="[
          'table-container',
          activeName === 'tab1' ? 'page-container' : 'list-container'
        ]"
      >
        <el-table
          ref="draggableTable"
          size="mini"
          :data="list"
          style="width: 100%;"
          v-loading="listLoading"
          row-key="id"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column
            type="selection"
            width="55"
            v-if="activeName === 'tab1'"
          >
          </el-table-column>
          <el-table-column label="广告ID" width="80" align="center">
            <template slot-scope="scope">{{ scope.row.goodsId }}</template>
          </el-table-column>
          <el-table-column label="广告名称" align="center">
            <template slot-scope="scope">{{ scope.row.goodsName }}</template>
          </el-table-column>
          <el-table-column label="最低价格" align="center">
            <template slot-scope="scope">{{ scope.row.minPrice }}</template>
          </el-table-column>
          <el-table-column label="最高价格" align="center">
            <template slot-scope="scope">{{ scope.row.maxPrice }}</template>
          </el-table-column>
          <el-table-column label="广告库存" align="center">
            <template slot-scope="scope">{{ scope.row.goodsStock }}</template>
          </el-table-column>
          <el-table-column label="排序" align="center">
            <template slot-scope="scope">{{ scope.row.sort }}</template>
          </el-table-column>
          <el-table-column label="派发状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.state == 0 ? 'danger' : 'success'">
                {{ scope.row.state == 0 ? "未" : "已" }}派发</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="160">
            <template slot-scope="scope">{{
              scope.row.createTime | formatDateTime
            }}</template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container" v-if="activeName === 'tab2'">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 添加广告配置 -->
      <goods-list-dialog
        v-if="goodsVisible"
        :goodsList="goodsList"
        @handle-confirm="handleConfirm"
        @handle-cancel="goodsVisible = false"
      />
    </div>
  </el-dialog>
</template>
<script>
import { getStorage, formatAmount } from "@/utils/index";
import { formatDate } from "@/utils/date";
import GoodsListDialog from "@/views/goods/list/list.vue";
import Sortable from "sortablejs";
import {
  getGoodsConfigList,
  getGoodsConfigPageList,
  deleteGoodsConfig,
  sortGoodsConfig,
  addGoodsConfig,
  dispatchGoodsConfig,
  cancelGoodsConfig
} from "@/api/member";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10
};
export default {
  components: {
    GoodsListDialog
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      loading: false,
      listLoading: false,
      stateObj: {},
      visible: true,
      goodsVisible: false,
      goodsList: [],
      activeName: "tab1",
      selectedRows: []
    };
  },
  props: {
    row: {
      type: Object,
      default: {}
    }
  },
  created() {
    this.getLoad();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    formatAmount,
    handleCloseDialog() {
      this.$emit("handle-cancel");
    },
    //排序
    initDragSort() {
      let el = this.$refs.draggableTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {
        onEnd: evt => {
          const curRow = this.list.splice(evt.oldIndex, 1)[0];
          this.list.splice(evt.newIndex, 0, curRow);
          this.saveSortOrder(this.list);
        }
      });
    },

    // 保存排序到后端的方法示例
    saveSortOrder(data) {
      const list = data.map((item, index) => {
        return {
          id: item.id,
          sort: index + 1
        };
      });
      sortGoodsConfig({ list }).then(response => {
        this.getLoad();
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dataObject = Object.assign({}, defaultObject);
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    //选中内容
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    //切换tab
    handleClick(tab) {
      if (tab.name === "tab1") {
        this.getLoad();
        return;
      }
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //添加广告配置
    handleAdd() {
      this.goodsVisible = true;
    },

    //派发操作做
    handleOption(type) {
      if (this.selectedRows.length === 0) {
        this.$message({
          message: "请选择内容后在操作",
          type: "error",
          duration: 1000
        });
        return;
      }
      const ids = this.selectedRows.map(item => item.id);
      //派单
      if (type == 1) {
        dispatchGoodsConfig({ ids }).then(response => {
          this.$message({
            message: "派单成功",
            type: "success",
            duration: 1000
          });
          this.getLoad();
        });
        return;
      }
      //取消派单
      cancelGoodsConfig({ ids }).then(response => {
        this.$message({
          message: "取消派单成功",
          type: "success",
          duration: 1000
        });
        this.getLoad();
      });
    },

    //添加广告配置
    handleConfirm(val) {
      this.goodsList = val;
      this.goodsVisible = false;
      const goodsIds = val.map(item => item.id);
      addGoodsConfig({ goodsIds, memberId: this.row.id }).then(response => {
        this.$message({
          message: "添加成功",
          type: "success",
          duration: 1000
        });
        this.getLoad();
      });
    },

    //删除
    handleDelete(row) {
      this.$confirm("是否要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteGoodsConfig({ id: row.id }).then(response => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          if (this.activeName === "tab1") {
            this.getLoad();
            return;
          }
          this.getList();
        });
      });
    },
    //未下单列表
    getLoad() {
      this.listLoading = true;
      let params = { memberId: this.row.id };
      getGoodsConfigList(params).then(response => {
        this.listLoading = false;
        this.list = response.data || [];
        this.initDragSort();
      });
    },
    //已下单列表
    getList() {
      this.listLoading = true;
      let params = { ...this.listQuery, memberId: this.row.id };
      getGoodsConfigPageList(params).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    }
  }
};
</script>
<style scoped lang="scss">
.img-box {
  img {
    width: 50px;
    height: 50px;
    border: solid 1px #eee;
    cursor: pointer;
  }
}
.input-width {
  width: 140px;
}
</style>

<style lang="scss">
.page-container {
  height: calc(100vh - 550px);
  .el-table__body-wrapper {
    height: calc(100vh - 600px);
    overflow-y: auto;
  }
}
.list-container {
  height: calc(100vh - 600px);
  .el-table__body-wrapper {
    height: calc(100vh - 640px);
    overflow-y: auto;
  }
}
.edit-goods-dialog {
  .el-dialog__body {
    height: 60vh !important;
    overflow: hidden;
    padding: 0 16px;
  }
}
/* 拖拽时的样式 */
::v-deep .sortable-ghost {
  opacity: 0.5;
  background-color: #f5f7fa;
}

.draggable-table-container {
  margin: 20px;
}
.options-btns {
  position: absolute;
  right: 25px;
  top: 60px;
}
</style>
